package com.wkh.project.rules.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.lang.generator.SnowflakeGenerator;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wkh.project.model.entity.rule.RewardRule;
import com.wkh.project.model.form.rules.RewardRuleRequest;
import com.wkh.project.model.form.rules.RewardRuleRequestForm;
import com.wkh.project.model.vo.rules.RewardRuleResponse;
import com.wkh.project.model.vo.rules.RewardRuleResponseVo;
import com.wkh.project.rules.mapper.RewardRuleMapper;
import com.wkh.project.rules.service.RewardRuleService;
import com.wkh.project.rules.utils.DroolsHelper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.kie.api.runtime.KieSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class RewardRuleServiceImpl implements RewardRuleService {

    @Resource
    private RewardRuleMapper rewardRuleMapper;
    private static final String RULES_CUSTOMER_RULES_DRL = "rules/RewardRule.drl";

    @Override
    public RewardRuleResponseVo calculateOrderRewardFee(RewardRuleRequestForm rewardRuleRequestForm) {
        //封装参数
        RewardRuleRequest rewardRuleRequest = new RewardRuleRequest();
        rewardRuleRequest.setOrderNum(rewardRuleRequestForm.getOrderNum());
        String startTime = new DateTime(rewardRuleRequestForm.getStartTime()).toString("yyyy-MM-dd");
        rewardRuleRequest.setStartTime(startTime);
        //获取最新订单费用规则
//        RewardRule rewardRule = rewardRuleMapper.selectOne(new LambdaQueryWrapper<RewardRule>().orderByDesc(RewardRule::getId).last("limit 1"));
        //创建规则引擎对象
        KieSession kieSession = DroolsHelper.loadForRule(RULES_CUSTOMER_RULES_DRL);
        //封装返回对象
        RewardRuleResponse rewardRuleResponse = new RewardRuleResponse();
        kieSession.setGlobal("rewardRuleResponse",rewardRuleResponse);
        //设置对象，触发规则
        kieSession.insert(rewardRuleRequest);
        kieSession.fireAllRules();
        //终止会话
        kieSession.dispose();
        //封装RewardRuleResponseVo对象
        RewardRuleResponseVo rewardRuleResponseVo = new RewardRuleResponseVo();
        rewardRuleResponseVo.setRewardAmount(rewardRuleResponse.getRewardAmount());
        rewardRuleResponseVo.setRewardRuleId(IdUtil.getSnowflakeNextId());
        return rewardRuleResponseVo;
    }
}
